package com.example.fast.common.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.ExceptionUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * CommonUtils
 */
@UtilityClass
@Slf4j
public class ExceptionUtils {

    /**
     * from {@link ExceptionUtil#unwrapThrowable(Throwable)}
     */
    public static Throwable unwrapThrowable(Throwable wrapped) {
        Throwable unwrapped = wrapped;
        while (true) {
            if (unwrapped instanceof InvocationTargetException) {
                unwrapped = ((InvocationTargetException) unwrapped).getTargetException();
            } else if (unwrapped instanceof UndeclaredThrowableException) {
                unwrapped = ((UndeclaredThrowableException) unwrapped).getUndeclaredThrowable();
            } else {
                return unwrapped;
            }
        }
    }

    /**
     * from {@link org.apache.rocketmq.remoting.common.RemotingHelper#exceptionSimpleDesc(Throwable)}
     */
    public static String exceptionSimpleDesc(final Throwable e) {
        StringBuilder sb = new StringBuilder();
        if (e != null) {
            sb.append(e.toString());

            StackTraceElement[] stackTrace = e.getStackTrace();
            if (stackTrace != null && stackTrace.length > 0) {
                StackTraceElement element = stackTrace[0];
                sb.append(", ").append(element.toString());

                if (stackTrace.length > 1) {
                    StackTraceElement element2 = stackTrace[1];
                    sb.append(", ").append(element2.toString());
                }
            }
        }

        return sb.toString();
    }
}
